package com.xneure.enging.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import com.xneure.enging.RequestContext;
import com.xneure.enging.WebContext;
import com.xneure.utils.FileUtil;
import com.xneure.utils.JsonUtil;

public class UiEntry extends UiElement{
	private static List<String> css = new ArrayList<String>();
	private static List<String> js = new ArrayList<String>();
	private String title;
	static{
		loadResources();
	}

	public UiEntry(){
		super(null);
		RequestContext.getEventNotify(WebContext.getSession().getId());
	}

	private static void loadResources(){
		try{
			String resDir = "META-INF/resources/";
			List<String> rs = FileUtil.getResourcesJar(resDir);
			int index = resDir.length();
			for(String path:rs){
				ZipFile file = new ZipFile(path);
				Enumeration<? extends ZipEntry> entries = file.entries();
				while(entries.hasMoreElements()){
					ZipEntry zipEntry = (ZipEntry)entries.nextElement();
					String fileName = zipEntry.getName();
					if(fileName.startsWith(resDir)){
						if(zipEntry.getSize() > 0){
							if(fileName.endsWith(".css")){
								css.add(fileName.substring(index));
							}else if(fileName.endsWith(".js")){
								js.add(fileName.substring(index));
							}
						}
					}
				}
				file.close();
			}
		}catch(IOException e){
		}
	}

	String toHtml(){
		StringBuffer htmlData = new StringBuffer();
		htmlData.append("<!DOCTYPE html>\r\n");
		htmlData.append("<html>\r\n");
		htmlData.append("<head>\r\n");
		htmlData.append("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />\r\n");
		loadCSS(htmlData,css);
		loadJS(htmlData,js);
		htmlData.append("<title>\r\n");
		htmlData.append(this.title);
		htmlData.append("</title>\r\n");;
		htmlData.append("</head>\r\n");
		htmlData.append("</html>\r\n");
		htmlData.append("<script type= 'text/javascript'>\r\n");
		htmlData.append("initPage(");
		htmlData.append(JsonUtil.toJson(RequestContext.getEventNotify(WebContext.getSession().getId())));
		htmlData.append(");\r\n");
		htmlData.append("</script>");
		return htmlData.toString();
	}

	public void setTitle(String title){
		this.title = title;
	}

	private void loadJS(StringBuffer htmlData,Collection<String> f){
		if(null == f)
			return;
		for(String str:f){
			htmlData.append("<script src='" + str + "' type= 'text/javascript'></script>\r\n");
		}
	}

	private void loadCSS(StringBuffer htmlData,Collection<String> f){
		if(null == f)
			return;
		for(String str:f){
			htmlData.append("<link rel='stylesheet' href='" + str + "' type= 'text/css' />\r\n");
		}
	}

	@Override
	public String getType(){
		return null;
	}
}
